package com.ouyunc.oauth2.config.override;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ouyunc.common.constant.Auth2Constant;
import com.ouyunc.common.constant.RedisKeyConstant;
import com.ouyunc.common.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @Author fangzhenxun
 * @Description 自定义 RedisTokenStore 解决生成token相关在redis中的key值前缀
 * @Date 2020/7/6 15:41
 **/
@Slf4j
public class IRedisTokenStore implements TokenStore {

    /**
     * 默认的oauth2 token  的存储前缀，可以通过参数传递用户类型来进行动态设置,注意需要保证线程安全，使用threadlocal
     */
    private static final ThreadLocal<String> prefix = ThreadLocal.withInitial(() -> RedisKeyConstant.DEFAULT_OAUTH2_TOKEN_KEY_PREFIX);

    /**
     * 用户配置的默认动态redis前缀map： key=usertype,  value=prefix
     */
    private static final Map<String, String> prefixMap = new HashMap<>();



    private static final String ACCESS = "access:";
    private static final String ACCESS_TO_REFRESH = "access_to_refresh:";


    private static final String REFRESH ="refresh:";
    private static final String REFRESH_TO_ACCESS ="refresh_to_access:";


    private static final String AUTH = "auth:";
    private static final String AUTH_TO_ACCESS = "auth_to_access:";
    //自定义，过期日期和refresh一样只不过里面存的是refresh_token 的值
    private static final String AUTH_TO_REFRESH = "auth_to_refresh:";
    //自定义，模仿AUTH 来进行存储string 类型的当前登录用户，以方便在其他服务中进行获取当前登录人信息（不需要引入oauth2依赖）
    private static final String PRINCIPLE = "principle:";

    private static final String REFRESH_AUTH = "refresh_auth:";
    private static final String CLIENT_ID_TO_ACCESS ="client_id_to_access:";
    private static final String UNAME_TO_ACCESS ="uname_to_access:";


    private static final boolean springDataRedis_2_0 = ClassUtils.isPresent(
            "org.springframework.data.redis.connection.RedisStandaloneConfiguration",
            RedisTokenStore.class.getClassLoader());

    /**
     * redis连接工厂
     **/
    private final RedisConnectionFactory connectionFactory;

    /**
     * 认证key的生成器
     **/
    private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();

    /**
     * token在redis中存储的序列化策略
     **/
    private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();


    private Method redisConnectionSet_2_0;



    public IRedisTokenStore(RedisConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
        if (springDataRedis_2_0) {
            this.loadRedisConnectionMethods_2_0();
        }
    }

    public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
        this.authenticationKeyGenerator = authenticationKeyGenerator;
    }

    public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
        this.serializationStrategy = serializationStrategy;
    }

    /**
     * @Author fangzhenxun
     * @Description  get方法
     * @Date 2020/7/7 13:30
     * @param
     * @return java.lang.String
     **/
    public String getPrefix() {
        return prefix.get();
    }


    public void setPrefixMap(Map<String, String> redisPrefix) {
        if (MapUtils.isNotEmpty(redisPrefix)) {
            prefixMap.putAll(redisPrefix);
        }
    }


    private void loadRedisConnectionMethods_2_0() {
        this.redisConnectionSet_2_0 = ReflectionUtils.findMethod(
                RedisConnection.class, "set", byte[].class, byte[].class);
    }

    /**
     * @Author fangzhenxun
     * @Description  获取redis连接
     * @Date 2020/7/7 18:42
     * @param
     * @return org.springframework.data.redis.connection.RedisConnection
     **/
    private RedisConnection getConnection() {
        return connectionFactory.getConnection();
    }

    /**
     * @Author fangzhenxun
     * @Description  token 值的序列化
     * @Date 2020/7/7 18:43
     * @param object
     * @return byte[]
     **/
    private byte[] serialize(Object object) {
        return serializationStrategy.serialize(object);
    }

    /**
     * @Author fangzhenxun
     * @Description  这里动态进行从当前请求中获取扩展的参数
     * @Date 2020/7/7 13:31
     * @param object
     * @return byte[]
     **/
    private byte[] serializeKey(String object) {
        // 获取当前请求参数信息
        HttpServletRequest currentRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        // 从当前请求获取扩展信息,如果没有在从请求头
        String extendMapStr = currentRequest.getParameter(Auth2Constant.EXTEND_MAP);
        if (StringUtils.isBlank(extendMapStr)) {
            extendMapStr = currentRequest.getHeader(Auth2Constant.EXTEND_MAP);
        }
        if (StringUtils.isNotBlank(extendMapStr)) {
            // 从请求参数中获取扩展信息
            JSONObject extendMap = JSONObject.parseObject(extendMapStr);
            if (extendMap.containsKey(Auth2Constant.USER_TYPE) && prefixMap.containsKey(extendMap.get(Auth2Constant.USER_TYPE))) {
                // 设置prefix
                prefix.set(prefixMap.get(extendMap.get(Auth2Constant.USER_TYPE)));
            }
        }
        return serialize(prefix.get() + object);
    }


    private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
    }

    private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
    }

    private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
    }

    private byte[] serialize(String string) {
        return serializationStrategy.serialize(string);
    }

    private String deserializeString(byte[] bytes) {
        return serializationStrategy.deserializeString(bytes);
    }


    /**
     * @Author fangzhenxun
     * @Description 获取自定义的当前登录用户信息json字符串
     * @param accessToken
     * @return java.lang.String
     */
    public String readPrincipleByAccessToken(String accessToken) {
        byte[] principleKey = serializeKey(PRINCIPLE + accessToken);
        //根据accessToken 获取失效的principle
        RedisConnection conn = getConnection();
        try {
            byte[] principleBytes = conn.get(principleKey);
            return deserializeString(principleBytes);
        } finally {
            conn.close();
        }
    }


    /**
     * @Author fangzhenxun
     * @Description  根据accessToken获取OAuth2RefreshToken
     * @Date 2020/7/10 9:35
     * @param accessToken
     * @return org.springframework.security.oauth2.common.OAuth2RefreshToken
     **/
    public String readRefreshTokenByAccessToken(String accessToken) {
        byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + accessToken);
        //根据refreshToken 获取失效的accessToken
        RedisConnection conn = getConnection();
        try {
            byte[] refreshTokenBytes = conn.get(accessToRefreshKey);
            return deserializeString(refreshTokenBytes);
        } finally {
            conn.close();
        }
    }

    /**
     * @Author fangzhenxun
     * @Description  根据自定义的AUTH_TO_REFRESH 来 移除refresh_token相关的token，当access_token失效，refresh_token不失效的时候调用获取token接口
     * @Date 2020/7/9 16:33
     * @param authentication
     * @return void
     **/
    public void removeRefreshTokenWhenAccessTokenExpire(OAuth2Authentication authentication) {
        String key = authenticationKeyGenerator.extractKey(authentication);
        byte[] serializedKey = serializeKey(AUTH_TO_REFRESH + key);
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(serializedKey);
            //拿到refreshToken
            OAuth2RefreshToken oAuth2RefreshToken = deserializeRefreshToken(bytes);
            if (oAuth2RefreshToken != null && oAuth2RefreshToken.getValue() != null) {
                String refreshToken = oAuth2RefreshToken.getValue();

                //根据accessToken获取已存在的未失效的refresh_token 然后在删除相关的token
                byte[] refreshKey = serializeKey(REFRESH + refreshToken);
                byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken);
                byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + refreshToken);

                //根据refreshToken 获取失效的accessToken
                byte[] accessTokenBytes = conn.get(refresh2AccessKey);
                String accessToken = deserializeString(accessTokenBytes);
                byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + accessToken);

                conn.del(serializedKey);
                conn.del(refreshKey);
                conn.del(refreshAuthKey);
                conn.del(refresh2AccessKey);
                conn.del(access2RefreshKey);
            }
        } finally {
            conn.close();
        }
    }

    /**
     * @Author fangzhenxun
     * @Description 根据认证信息获取原有的token
     * @Date 2020/7/7 18:46
     * @param authentication
     * @return org.springframework.security.oauth2.common.OAuth2AccessToken
     **/
    @Override
    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
        String key = authenticationKeyGenerator.extractKey(authentication);
        byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(serializedKey);
        } finally {
            conn.close();
        }
        OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
        if (accessToken != null) {
            OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
            if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
                // Keep the stores consistent (maybe the same user is
                // represented by this authentication but the details have
                // changed)
                //为了多次登录保持最新的客户端用户信息
                storeAccessToken(accessToken, authentication);
            }

        }
        return accessToken;
    }

    @Override
    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
        return readAuthentication(token.getValue());
    }

    @Override
    public OAuth2Authentication readAuthentication(String token) {
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(serializeKey(AUTH + token));
        } finally {
            conn.close();
        }
        OAuth2Authentication auth = deserializeAuthentication(bytes);
        return auth;
    }

    @Override
    public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
        return readAuthenticationForRefreshToken(token.getValue());
    }

    public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
        RedisConnection conn = getConnection();
        try {
            byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token));
            OAuth2Authentication auth = deserializeAuthentication(bytes);
            return auth;
        } finally {
            conn.close();
        }
    }

    /**
     * @Author fangzhenxun
     * @Description  存储token
     * @Date 2020/7/8 19:21
     * @param token
     * @param authentication
     * @return void
     **/
    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        byte[] serializedAccessToken = serialize(token);
        byte[] serializedAuth = serialize(authentication);
        // 使用json序列化字符串
        byte[] serializedPrinciple = serialize(JSON.toJSONString(authentication.getPrincipal(), SerializerFeature.WriteMapNullValue));

        byte[] accessKey = serializeKey(ACCESS + token.getValue());
        byte[] authKey = serializeKey(AUTH + token.getValue());
        // 存储自定义的当前登录用户信息
        byte[] principleKey = serializeKey(PRINCIPLE + token.getValue());

        byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
        byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
        byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());

        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            if (springDataRedis_2_0) {
                try {
                    this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
                    this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
                    // 设置当前登录人缓存
                    this.redisConnectionSet_2_0.invoke(conn, principleKey, serializedPrinciple);

                    this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                conn.set(accessKey, serializedAccessToken);
                conn.set(authKey, serializedAuth);
                // 设置当前登录人信息
                conn.set(principleKey, serializedPrinciple);

                conn.set(authToAccessKey, serializedAccessToken);
            }
            if (!authentication.isClientOnly()) {
                conn.sAdd(approvalKey, serializedAccessToken);
            }
            conn.sAdd(clientId, serializedAccessToken);
            if (token.getExpiration() != null) {
                //这里只是设置 access_token 的key过期时间，默认情况下refresh_token还是第一次的过期时间
                //在这里可以就行修改，然后每次掉登录的接口的时候都会把所有的过期时间给设置原始的
                int seconds = token.getExpiresIn();
                conn.expire(accessKey, seconds);
                conn.expire(authKey, seconds);
                // 设置当前的登录人过期时间
                conn.expire(principleKey, seconds);
                conn.expire(authToAccessKey, seconds);
                conn.expire(clientId, seconds);
                conn.expire(approvalKey, seconds);
            }
            OAuth2RefreshToken refreshToken = token.getRefreshToken();

            if (refreshToken != null && refreshToken.getValue() != null) {
                byte[] refresh = serialize(token.getRefreshToken().getValue());

                //将refreshToken序列化
                byte[] serializedRefreshToken = serialize(refreshToken);

                byte[] auth = serialize(token.getValue());
                byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
                byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());

                //存储的时候将这也存进去
                byte[] authToRefreshKey = serializeKey(AUTH_TO_REFRESH + authenticationKeyGenerator.extractKey(authentication));

                //自定义，这里只是进行过期时间的设置
                byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
                byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());


                if (springDataRedis_2_0) {
                    try {
                        this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
                        this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
                        //自定义新增的时候走这里
                        this.redisConnectionSet_2_0.invoke(conn, authToRefreshKey, serializedRefreshToken);

                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                } else {
                    conn.set(refreshToAccessKey, auth);
                    conn.set(accessToRefreshKey, refresh);
                    //将自定义的存进去
                    conn.set(authToRefreshKey, serializedRefreshToken);
                }
                if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
                    ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
                    Date expiration = expiringRefreshToken.getExpiration();
                    if (expiration != null) {
                        int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
                                .intValue();
                        conn.expire(refreshToAccessKey, seconds);
                        conn.expire(accessToRefreshKey, seconds);
                        //下面可以加上刷新token的过期时间也给处理
                        //将refresh 与refresh_auth 也更新，注意：在第一次的时候虽然会执行但是没有对应的redis键来进行更新设置，不影响
                        conn.expire(refreshKey, seconds);
                        conn.expire(refreshAuthKey, seconds);
                        conn.expire(authToRefreshKey, seconds);
                    }
                }
            }
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }

    private static String getApprovalKey(OAuth2Authentication authentication) {
        String userName = authentication.getUserAuthentication() == null ? ""
                : authentication.getUserAuthentication().getName();
        return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
    }

    private static String getApprovalKey(String clientId, String userName) {
        return clientId + (userName == null ? "" : ":" + userName);
    }

    @Override
    public void removeAccessToken(OAuth2AccessToken accessToken) {
        removeAccessToken(accessToken.getValue());
    }

    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        byte[] key = serializeKey(ACCESS + tokenValue);
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(key);
        } finally {
            conn.close();
        }
        OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
        return accessToken;
    }

    public void removeAccessToken(String tokenValue) {
        byte[] accessKey = serializeKey(ACCESS + tokenValue);
        byte[] authKey = serializeKey(AUTH + tokenValue);
        // 自定义当前登录用户的key
        byte[] principleKey = serializeKey(PRINCIPLE + tokenValue);

        byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.get(accessKey);
            conn.get(authKey);
            // 获取当前登录人的key
            conn.get(principleKey);
            conn.del(accessKey);
            conn.del(accessToRefreshKey);
            // Don't remove the refresh token - it's up to the caller to do that
            conn.del(authKey);
            // 删除当前登录人的key
            conn.del(principleKey);
            List<Object> results = conn.closePipeline();
            byte[] access = (byte[]) results.get(0);
            byte[] auth = (byte[]) results.get(1);

            OAuth2Authentication authentication = deserializeAuthentication(auth);
            if (authentication != null) {
                String key = authenticationKeyGenerator.extractKey(authentication);
                byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
                byte[] unameKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
                byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
                conn.openPipeline();
                conn.del(authToAccessKey);
                conn.sRem(unameKey, access);
                conn.sRem(clientId, access);
                conn.del(serialize(ACCESS + key));
                conn.closePipeline();
            }
        } finally {
            conn.close();
        }
    }


    /**
     * @Author fangzhenxun
     * @Description  重载方法
     * @Date 2020/7/8 18:49
     * @param accessToken
     * @return void
     **/
    public void completelyRemoveAccessToken(OAuth2AccessToken accessToken) {
        completelyRemoveAccessToken(accessToken.getValue());
    }

    /**
     * @Author fangzhenxun
     * @Description 解决调用ConsumerTokenServices 中的移除会有UNAME_TO_ACCESS和CLIENT_ID_TO_ACCESS没有被删除
     * @Date 2020/7/8 18:44
     * @param tokenValue
     * @return void
     **/
    public void completelyRemoveAccessToken(String tokenValue) {
        byte[] accessKey = serializeKey(ACCESS + tokenValue);
        byte[] authKey = serializeKey(AUTH + tokenValue);
        // 当退出登录的时候可以删除自定义的的当前的登录人信息
        byte[] principleKey = serializeKey(PRINCIPLE + tokenValue);
        byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.get(accessKey);
            conn.get(authKey);
            // 获取当前登录人信息
            conn.get(principleKey);

            conn.del(accessKey);
            conn.del(accessToRefreshKey);
            // Don't remove the refresh token - it's up to the caller to do that
            conn.del(authKey);
            // 删除当前登录人信息
            conn.del(principleKey);
            List<Object> results = conn.closePipeline();
            byte[] access = (byte[]) results.get(0);
            byte[] auth = (byte[]) results.get(1);

            OAuth2Authentication authentication = deserializeAuthentication(auth);
            if (authentication != null) {
                String key = authenticationKeyGenerator.extractKey(authentication);
                byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
                //自定义的
                byte[] authToRefreshKey = serializeKey(AUTH_TO_REFRESH + key);
                byte[] unameKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
                byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
                conn.openPipeline();
                conn.del(authToAccessKey);
                //删除
                conn.del(authToRefreshKey);
                conn.del(unameKey);
                conn.del(clientId);
                conn.del(serialize(ACCESS + key));
                conn.closePipeline();
            }
        } finally {
            conn.close();
        }
    }

    @Override
    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
        byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
        byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
        byte[] serializedRefreshToken = serialize(refreshToken);
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            if (springDataRedis_2_0) {
                try {
                    this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
                    this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication));
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                conn.set(refreshKey, serializedRefreshToken);
                conn.set(refreshAuthKey, serialize(authentication));
            }
            if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
                ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
                Date expiration = expiringRefreshToken.getExpiration();
                if (expiration != null) {
                    int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
                            .intValue();
                    conn.expire(refreshKey, seconds);
                    conn.expire(refreshAuthKey, seconds);
                }
            }
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }

    @Override
    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
        byte[] key = serializeKey(REFRESH + tokenValue);
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(key);
        } finally {
            conn.close();
        }
        OAuth2RefreshToken refreshToken = deserializeRefreshToken(bytes);
        return refreshToken;
    }


    @Override
    public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
        removeRefreshToken(refreshToken.getValue());
    }

    /**
     * @Author fangzhenxun
     * @Description  这里进行了源码的修改
     * @Date 2020/7/10 10:02
     * @param tokenValue refreshToken
     * @return void
     **/
    public void removeRefreshToken(String tokenValue) {
        RedisConnection conn = getConnection();

        byte[] refreshKey = serializeKey(REFRESH + tokenValue);
        byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue);
        byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue);
        //这里有问题，传的是refreshToken,需要改正，根据refreshToken获取accessToken然后在进行删除
        //根据refreshToken 获取失效的accessToken
        byte[] accessTokenBytes = conn.get(refresh2AccessKey);
        String accessToken = deserializeString(accessTokenBytes);
        byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + accessToken);

        //获取auth,为了进一步获取key
        byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + tokenValue));
        //获取认证信息
        OAuth2Authentication authentication = deserializeAuthentication(bytes);
        String key = null;
        if (authentication != null) {
            key = authenticationKeyGenerator.extractKey(authentication);
        }
        //自定义的
        byte[] authToRefreshKey = serializeKey(AUTH_TO_REFRESH + key);

        try {
            conn.openPipeline();
            conn.del(refreshKey);
            conn.del(refreshAuthKey);
            conn.del(refresh2AccessKey);
            conn.del(access2RefreshKey);
            conn.del(authToRefreshKey);
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }

    @Override
    public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
        removeAccessTokenUsingRefreshToken(refreshToken.getValue());
    }

    private void removeAccessTokenUsingRefreshToken(String refreshToken) {
        byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
        List<Object> results = null;
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.get(key);
            conn.del(key);
            results = conn.closePipeline();
        } finally {
            conn.close();
        }
        if (results == null) {
            return;
        }
        byte[] bytes = (byte[]) results.get(0);
        String accessToken = deserializeString(bytes);
        if (accessToken != null) {
            removeAccessToken(accessToken);
        }
    }

    private List<byte[]> getByteLists(byte[] approvalKey, RedisConnection conn) {
        List<byte[]> byteList;
        Long size = conn.sCard(approvalKey);
        byteList = new ArrayList<byte[]>(size.intValue());
        Cursor<byte[]> cursor = conn.sScan(approvalKey, ScanOptions.NONE);
        while(cursor.hasNext()) {
            byteList.add(cursor.next());
        }
        return byteList;
    }

    @Override
    public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
        byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(clientId, userName));
        List<byte[]> byteList = null;
        RedisConnection conn = getConnection();
        try {
            byteList = getByteLists(approvalKey, conn);
        } finally {
            conn.close();
        }
        if (byteList == null || byteList.size() == 0) {
            return Collections.<OAuth2AccessToken> emptySet();
        }
        List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(byteList.size());
        for (byte[] bytes : byteList) {
            OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
            accessTokens.add(accessToken);
        }
        return Collections.<OAuth2AccessToken> unmodifiableCollection(accessTokens);
    }

    @Override
    public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
        byte[] key = serializeKey(CLIENT_ID_TO_ACCESS + clientId);
        List<byte[]> byteList = null;
        RedisConnection conn = getConnection();
        try {
            byteList = getByteLists(key, conn);
        } finally {
            conn.close();
        }
        if (byteList == null || byteList.size() == 0) {
            return Collections.<OAuth2AccessToken> emptySet();
        }
        List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(byteList.size());
        for (byte[] bytes : byteList) {
            OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
            accessTokens.add(accessToken);
        }
        return Collections.<OAuth2AccessToken> unmodifiableCollection(accessTokens);
    }
}
